#!/usr/bin/env python
#encoding:utf-8
import os
import time
import json
from mysqlClass import mysqlClass

def getDate(offsetDay = 0):
    timestamp = time.time()
    if offsetDay != 0:
        timestamp += offsetDay * 86400
    DATE_TIME = time.localtime(timestamp)
    return time.strftime('%Y-%m-%d', DATE_TIME)

if __name__ == "__main__":
    clearLogConfig = os.getenv("CLEAR_LOG_CONFIG")
    clearLogConfig = json.loads(clearLogConfig)
    for item in clearLogConfig:
        config = {
            "host": item["host"],
            "port": item["port"],
            "db": item["db"],
            "user": item["user"],
            "passwd": item["passwd"],
            "charset": "utf8"
        }
        DB = mysqlClass(config)
        for tableField in item["target"]:
            date = getDate(0 - tableField["save_day"])
            if tableField["date_time"] == "date":
                sql = " delete from %s where %s between '1970-01-01' and '%s' limit 10000 " % (tableField["table"], tableField["field"], date)
            else:
                sql = " delete from %s where %s between '1970-01-01 00:00:00' and '%s 23:59:59' limit 10000 " % (tableField["table"], tableField["field"], date)
            print sql
            DB.execute(sql)
